package com.liang;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁：ReadWriteLock
 *  写写/读写 需要"互斥"
 *  读读 不需要"互斥"
 *
 * @author: Liangxp
 * @date: 2019/8/3 11:42
 */
public class TestReadWriteLock10 {
    public static void main(String[] args) {
        ReadWriteLockDemo readWriteLockDemo = new ReadWriteLockDemo();

        new Thread(new Runnable() {
            @Override
            public void run() {
                readWriteLockDemo.write((int) (Math.random() * 101));
            }
        }, "write").start();


        for (int i = 1; i <= 100; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    readWriteLockDemo.read();
                }
            }, "read" + i).start();
        }


    }
}


class ReadWriteLockDemo {
    private int number = 0;

    // 读写锁
    private ReadWriteLock lock = new ReentrantReadWriteLock();

    // 读
    public void read() {
        // 上锁
        lock.readLock().lock();

        try {
            System.out.println(Thread.currentThread().getName() + " : " + number);
        } finally {
            // 释放锁
            lock.readLock().unlock();
        }
    }


    public void write(int number) {
        lock.writeLock().lock();

        try {

            System.out.println(Thread.currentThread().getName() + " : " + number);
            this.number = number;
        } finally {
            lock.writeLock().unlock();
        }
    }

}
